package com.gopay.checkorder.service.impl.expay;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.UmPayConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.umpay.mtpay.UmPayMtPayMessage;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.MoneyUtil;
import com.gopay.remote.bank.ExPayInteractRemoteService;

/**
 * 联动优势无卡订单查询类
 * 
 * @CheckOrderUmPayImpl.java
 * @author 
 * 
 */
public class CheckOrderUmPayMtPayImpl implements BankOrderService {
	private Logger logger = Logger.getLogger("UMPAY");
	@Resource(name = "bankExPayClient")
	private ExPayInteractRemoteService bankExPayClient;
	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String arg1) {
		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		checkOrderResult.setOrderId(bankOrder.getOrderId());
		
		UmPayMtPayMessage message = new UmPayMtPayMessage();
		String merDate = bankOrder.getOrderId().substring(0,8);
		message.setMerDate(merDate);
		message.setOrderId(bankOrder.getOrderId()); // 国付宝系统订单号
		message.setBankOrderId(bankOrder.getOutOrderId());
		message.setBank(BankConstants.BANK_LOGO_UMPAY);
	    message.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
	    message.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
		message.setOrderDate(DateUtils.format(bankOrder.getSendBankTm(),"yyyyMMdd"));
		message.setBank(bankOrder.getBankCode());

		Result result = new Result();
		try {
			result = bankExPayClient.queryOrder(message);
			if (result == null || !result.isSuccess()) {
				logger.error("bankClient fail.");
				if(result ==null || ProcCodeConstants.PROC_CODE_100E6058.equals(result.getResultCode())){
					BankCountDownLatch.failIncrease(bankOrder.getBankCode());
				}				
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				return checkOrderResult;
			}

			UmPayMtPayMessage res = (UmPayMtPayMessage) result.getDefaultModel();
			if (res == null) {
				// 查询结果为空
				logger.error("fail:orderId:" + bankOrder.getOrderId()+ " errcode:" + ProcCodeConstants.PROC_CODE_100E6022+ " err:bis query is null.");
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("银行返回对账结果为空");
				return checkOrderResult;
			}

			String retCode = res.getRetCode(); // 返回码
			String retMsg = res.getRetMsg(); // 返回信息
			String errorCode = res.getErrorCode(); // 交易错误码
			String tradeStatus = res.getTradeState(); // 订单状态
			//成功处理
			if (UmPayConstants.TRADE_SUCCESS.equals(tradeStatus)) {
				checkOrderResult.setSuccess(true);
				InAccInfo accInfo = new InAccInfo();
				accInfo.setOrderId(bankOrder.getOrderId());
				accInfo.setAmount(new BigDecimal(MoneyUtil.formatAmt(res.getAmt())));
				accInfo.setRetCode("00");
				accInfo.setCardType(BankCardType.Unknown.toString());
				checkOrderResult.setAccInfo(accInfo);
				logger.error("联动优势信用卡无卡支付订单：" + bankOrder.getOrderId() + "的交易成功"+ "返回码：" + retCode + "返回信息：" + retMsg);
			}
			//失败处理
			else if (UmPayConstants.TRADE_FAIL.equals(tradeStatus)) {
			    InAccInfo accInfo = new InAccInfo();
                accInfo.setOrderId(bankOrder.getOrderId());
                accInfo.setAmount(new BigDecimal(MoneyUtil.formatAmt(res.getAmt())));
                accInfo.setRetCode("01");
                accInfo.setCardType(BankCardType.Unknown.toString());
                checkOrderResult.setAccInfo(accInfo);
				checkOrderResult.setBankFailure(true);
				checkOrderResult.setErrMsg("银行返回交易失败");
				logger.error("联动优势信用卡无卡支付订单：" + bankOrder.getOrderId() + "的交易失败"+ "返回码：" + retCode + "返回信息：" + retMsg + "错误码："+ errorCode);
			}
			//不处理
			else if (UmPayConstants.TRADE_CANCEL.equals(tradeStatus)) {
				// 交易撤销
				checkOrderResult.setErrMsg("银行返回交易已撤销");
				logger.error("联动优势信用卡无卡支付订单：" + bankOrder.getOrderId() + "的交易撤销"+ "返回码：" + retCode + "返回信息：" + retMsg);
			} else if (UmPayConstants.TRADE_CLOSED.equals(tradeStatus)) {
				// 交易关闭
				checkOrderResult.setErrMsg("银行返回交易已关闭");
				logger.error("联动优势信用卡无卡支付订单：" + bankOrder.getOrderId() + "的交易关闭"+ "返回码：" + retCode + "返回信息：" + retMsg);
			} else if (UmPayConstants.WAIT_BUYER_PAY.equals(tradeStatus)) {
				// 交易等待付款
				checkOrderResult.setErrMsg("银行返回交易等待付款");
				logger.error("联动优势信用卡无卡支付订单：" + bankOrder.getOrderId()+ "的交易等待付款" + "返回码：" + retCode + "返回信息：" + retMsg);
			} else {
				checkOrderResult.setErrMsg("银行返回交易状态不明");
				logger.error("联动优势信用卡无卡支付订单：" + bankOrder.getOrderId() + "查询失败"+ "返回码：" + retCode + "返回信息：" + retMsg + "错误码："+ errorCode + "订单状态：" + tradeStatus);
			}
			return checkOrderResult;
		} catch (Exception e) {
			logger.error("bankClient fail.", e);
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("银行对账异常");
			return checkOrderResult;
		}
	}
	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}
}
